<template>
  <view class="container">
    <!-- 顶部用户信息 -->
    <view class="header">
      <view class="user-info">
        <text class="welcome">你好，{{ userInfo.name || '用户' }}</text>
        <text class="balance">积分余额：{{ accountInfo.pointBalance || 0 }}分</text>
      </view>
      <view class="share-btn" @click="handleShare">
        <text class="icon">📤</text>
        <text class="text">分享</text>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-input">
        <text class="search-icon">🔍</text>
        <input 
          class="input" 
          v-model="searchKeyword" 
          placeholder="搜索商品名称"
          placeholder-class="placeholder"
          @confirm="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-list">
      <view class="list-header">
        <text class="title">商品列表</text>
        <text class="count">共{{ total }}件商品</text>
      </view>
      
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <view v-else-if="productList.length === 0" class="empty">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无商品</text>
      </view>
      
      <view v-else class="products">
        <view 
          class="product-item" 
          v-for="item in productList" 
          :key="item.id"
          @click="goToDetail(item.id)"
        >
          <view class="product-info">
            <text class="product-name">{{ item.name }}</text>
            <text class="merchant-name">{{ item.merchantName }}</text>
            <text class="product-attr">{{ item.attribute }}</text>
          </view>
          <view class="product-price">
            <text class="price">{{ formatPrice(item.price) }}</text>
            <text class="stock">库存：{{ item.num }}</text>
          </view>
          <view class="product-action">
            <button 
              class="buy-btn" 
              :disabled="item.num <= 0"
              @click.stop="handleBuy(item)"
            >
              {{ item.num <= 0 ? '缺货' : '立即购买' }}
            </button>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more">
        <button class="load-more-btn" @click="loadMore">加载更多</button>
      </view>
    </view>
  </view>
</template>

<script>
import { getProductList } from '@/api/product.js'
import { createOrder, payOrder } from '@/api/order.js'
import { generateDownloadQR } from '@/api/qrcode.js'
import { getCurrentUser, getCurrentAccount } from '@/api/user.js'
import { getUserInfo } from '@/utils/auth.js'

export default {
  data() {
    return {
      userInfo: {}, // 用户信息
      accountInfo: {}, // 账户信息
      productList: [], // 商品列表
      searchKeyword: '', // 搜索关键词
      loading: false, // 加载状态
      hasMore: true, // 是否还有更多
      pageIndex: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0 // 总数量
    }
  },
  onLoad() {
    this.init()
  },
  onShow() {
    // 每次显示页面时刷新用户信息
    this.loadUserInfo()
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.refresh()
  },
  onReachBottom() {
    // 上拉加载更多
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    // 初始化
    async init() {
      await this.loadUserInfo()
      this.loadProductList()
    },
    
    // 加载用户信息
    async loadUserInfo() {
      try {
        // 获取用户信息
        const userRes = await getCurrentUser()
        this.userInfo = userRes.data
        
        // 获取账户信息
        const accountRes = await getCurrentAccount()
        this.accountInfo = accountRes.data
        
      } catch (error) {
        console.error('加载用户信息失败:', error)
      }
    },
    
    // 加载商品列表
    async loadProductList(isRefresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
          pageIndex: isRefresh ? 1 : this.pageIndex,
          pageSize: this.pageSize
        }
        
        // 如果有搜索关键词，添加到参数中（这里需要根据实际接口调整）
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }
        
        const res = await getProductList(params)
        
        if (isRefresh) {
          this.productList = res.data.list || []
          this.pageIndex = 1
        } else {
          this.productList = [...this.productList, ...(res.data.list || [])]
        }
        
        this.total = res.data.total || 0
        this.hasMore = this.productList.length < this.total
        
        if (!isRefresh) {
          this.pageIndex++
        }
        
      } catch (error) {
        console.error('加载商品列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 搜索
    handleSearch() {
      this.refresh()
    },
    
    // 刷新
    refresh() {
      this.pageIndex = 1
      this.hasMore = true
      this.loadProductList(true)
    },
    
    // 加载更多
    loadMore() {
      this.loadProductList()
    },
    
    // 跳转商品详情
    goToDetail(productId) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${productId}`
      })
    },
    
    // 立即购买
    async handleBuy(product) {
      if (product.num <= 0) {
        uni.showToast({
          title: '商品缺货',
          icon: 'none'
        })
        return
      }
      
      try {
        // 显示数量选择弹窗
        const result = await this.showQuantityDialog()
        if (!result.confirm) return
        
        const quantity = result.content
        
        uni.showLoading({
          title: '创建订单中...'
        })
        
        // 创建订单
        const orderRes = await createOrder({
          productId: product.id,
          num: quantity,
          merchantId: product.merchantId
        })
        
        uni.hideLoading()
        
        // 跳转到支付页面
        uni.navigateTo({
          url: `/pages/order/pay?orderId=${orderRes.data.orderId}&amount=${orderRes.data.amount}&pointAmount=${orderRes.data.pointAmount}`
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('购买失败:', error)
      }
    },
    
    // 显示数量选择弹窗
    showQuantityDialog() {
      return new Promise((resolve) => {
        uni.showModal({
          title: '选择数量',
          editable: true,
          placeholderText: '请输入购买数量',
          success: (res) => {
            if (res.confirm) {
              const quantity = parseInt(res.content)
              if (quantity && quantity > 0) {
                resolve({ confirm: true, content: quantity })
              } else {
                uni.showToast({
                  title: '请输入有效数量',
                  icon: 'none'
                })
                resolve({ confirm: false })
              }
            } else {
              resolve({ confirm: false })
            }
          }
        })
      })
    },
    
    // 分享
    async handleShare() {
      try {
        uni.showLoading({
          title: '生成二维码中...'
        })
        
        const res = await generateDownloadQR()
        
        uni.hideLoading()
        
        // 显示二维码
        uni.showModal({
          title: '分享下载二维码',
          content: '点击确定保存二维码到相册',
          success: (modalRes) => {
            if (modalRes.confirm) {
              // 保存图片到相册
              uni.saveImageToPhotosAlbum({
                filePath: res.data,
                success: () => {
                  uni.showToast({
                    title: '保存成功',
                    icon: 'success'
                  })
                },
                fail: () => {
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            }
          }
        })
        
      } catch (error) {
        uni.hideLoading()
        console.error('分享失败:', error)
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    },
    
    // 格式化价格
    formatPrice(price) {
      return (price / 100).toFixed(2) + '元'
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  color: #fff;
}

.welcome {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.balance {
  font-size: 24rpx;
  opacity: 0.8;
}

.share-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  background: rgba(255, 255, 255, 0.1);
}

.share-btn .icon {
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.share-btn .text {
  font-size: 24rpx;
}

.search-box {
  padding: 30rpx;
  background: #fff;
  margin-bottom: 20rpx;
}

.search-input {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
}

.search-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
  color: #999;
}

.input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.placeholder {
  color: #999;
}

.search-btn {
  margin-left: 20rpx;
  padding: 12rpx 24rpx;
  background: #667eea;
  color: #fff;
  font-size: 24rpx;
  border-radius: 8rpx;
  border: none;
}

.search-btn::after {
  border: none;
}

.product-list {
  padding: 0 30rpx;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.count {
  font-size: 24rpx;
  color: #999;
}

.loading, .empty {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.product-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.product-info {
  flex: 1;
  margin-right: 20rpx;
}

.product-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.merchant-name {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.product-attr {
  font-size: 22rpx;
  color: #999;
  display: block;
}

.product-price {
  text-align: right;
  margin-right: 20rpx;
}

.price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
  display: block;
  margin-bottom: 8rpx;
}

.stock {
  font-size: 22rpx;
  color: #999;
}

.buy-btn {
  padding: 16rpx 32rpx;
  background: #667eea;
  color: #fff;
  font-size: 24rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
}

.buy-btn::after {
  border: none;
}

.buy-btn[disabled] {
  background: #ccc;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 30rpx 0;
}

.load-more-btn {
  padding: 20rpx 60rpx;
  background: #fff;
  color: #667eea;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: 2rpx solid #667eea;
}

.load-more-btn::after {
  border: none;
}
</style>